<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\WechatController;
use App\Models\Role;
use App\Repositories\Eloquent\UserRepositoryEloquent;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserRequest;
use App\User;

class UserController extends Controller
{
    const CACHE_UPDATE_WECHAT_QRCODE_KEY = 'cache_update_wechat_qrcode_key_';
    private $user;

    function __construct(UserRepositoryEloquent $user)
    {
        $this->user = $user;
    }

    /**
     * 查看用户信息
     */
    public function index()
    {
        $user = getUser();
        list($wechat['url'], $wechat['qrcode']) = WechatController::qrcode(self::CACHE_UPDATE_WECHAT_QRCODE_KEY . $user->id,
            self::class, 'updateWechat', [$user->id]);
        return view('auth.user.show')->with(compact('user', 'wechat'));
    }

    //扫码回调函数，更新微信openid
    public static function updateWechat($id, $openid)
    {
        $user = User::find($id);
        if ($user && !empty($openid)) {
            $userService = WechatController::app()->user;
            $user->openid = $openid;
            $u = $userService->get($openid);
            $user->headimgurl = $u->headimgurl;
            $user->save();
            return "亲爱的管理员，" . $user->name . "，恭喜你更新微信信息成功[愉快]";
        }
        return "更新失败，请重试[难过]";
    }


    /**
     * 修改用户视图
     */
    public function edit()
    {
        $user = getUser();
        return view('auth.user.edit')->with(compact('user'));
    }

    /**
     * 修改用户
     */
    public function update(UserRequest $request)
    {
        $data = [
            'name' => $request->input('name'),
            'username' => $request->input('username'),
            'email' => $request->input('email'),
            'password' => $request->input('password'),
        ];
        $this->user->update($data, getUerId());
        return redirect('user');
    }
}
